<template>
  <div class="">
    <public-table :table-option="tableOption" :table-data="tableData" :height="550" :page="pageParam"
      @page-change="onPageChange" radio @handleSelectionChange="onSelectChange">
      <el-form @submit.native.prevent>
        <el-row>
          <el-col :span="6" class="p-r10">
            <el-form-item label="申请时间">
              <el-date-picker v-model="searchParam.applyTime" type="daterange" range-separator="-"
                start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="6" class="p-r10">
            <el-form-item label="审批状态">
              <el-select v-model="searchParam.approvalStatus" placeholder="请选择审批状态" clearable style="width: 100%;">
                <el-option v-for="item in stateOptions" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="p-r10">
            <el-form-item label="推送状态">
              <el-select v-model="searchParam.pushStatus" placeholder="请选择推送状态" clearable style="width: 100%;">
                <el-option v-for="item in pushOptions" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="p-r10">
            <el-form-item label="开票状态">
              <el-select v-model="searchParam.billingStatus" placeholder="请选择开票状态" clearable style="width: 100%;">
                <el-option v-for="item in invoiceStateOptions" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" class="p-r10">
            <el-form-item label="发票号码">
              <el-input v-model="searchParam.receiptNumber" placeholder="请输入发票号码" clearable style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="18" style="display: flex;align-items: center;" class="p-r10">
            <el-form-item>
              <div class="d-flex">
                <el-button class="button_view" @click="searchHandler">查询</el-button>
                <el-button color="#f0f0f0" style="color: #000000" @click="resetHandler">重置</el-button>
              </div>
              <el-divider direction="vertical" />
              <div class="d-flex">
                <el-button class="button_edit" @click="exportHandler">
                  <svg-icon icon-class="project-detail-icon-derive" class="icon-export m-r5"></svg-icon>一键导出
                </el-button>
              </div>
              <div class="d-flex">
<!--                <el-button class="button_edit" @click="optionHandler('invalid')">作废</el-button>-->
                <el-button class="button_edit" @click="optionHandler('replace')">红冲</el-button>
                <el-button class="button_edit" @click="optionHandler('push')">推送</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #operate="{ row }">
        <el-button size="small" class="button_view" @click="viewHandler(row)" :disabled="row.billingStatus === 0">
          查看发票
        </el-button>
        <el-button size="small" class="button_edit" @click="detailHandler(row)">详情</el-button>
      </template>
    </public-table>

      <el-dialog
              v-model="dialogVisible"
              title="红冲发票"
              width="30%"
              :before-close="()=>{dialogVisible = false;form.status=''}"
      >
          <div class="d-flex a-center">
              <span>红冲原因:</span>
              <el-select v-model="form.status" placeholder="请选择" clearable style="flex: 1;margin-left: 10px;">
                  <el-option label="销货退回" value="1"></el-option>
                  <el-option label="开票有误" value="2"></el-option>
                  <el-option label="开票中止" value="3"></el-option>
                  <el-option label="销售折让" value="4"></el-option>
              </el-select>
          </div>
          <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false;form.status=''">取消</el-button>
        <el-button class="button_view" type="primary" @click="confirm()">
          确认
        </el-button>
      </span>
          </template>
      </el-dialog>
  </div>

    <imgDialog ref="imgDialogRef" />
    <imgDialog2 ref="imgDialogRef2" />
    <infoDialog ref="infoDialogRef" />
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import {
    ElButton,
    ElForm,
    ElFormItem,
    ElInput,
    ElDatePicker,
    ElSelect,
    ElOption,
    ElNotification,
    ElRow,
    ElCol,
    ElDivider,
    ElMessageBox,
    ElMessage,
    ElDialog, ElLoading
} from "element-plus";
import PublicTable from "@/components/PublicTable.vue";
import ImgDialog from "./components/imgDialog.vue";
import ImgDialog2 from "./components/imgDialog2.vue";
import InfoDialog from "./components/infoDialog.vue";
import { invoiceListApi } from "@/api/businessFinance.js";
import {downloadFile, exportFile} from "@/common/utils/GlobalUtils.js";

const dialogVisible = ref(false);
const form = reactive({status:''});

let tableOption = ref([
  {
    prop: "receiptId",
    label: "开票编码",
    minWidth: 100,
  },
  {
    prop: "receiptNumber",
    label: "发票号码",
    minWidth: 100,
  },
  {
    prop: "receiptCode",
    label: "发票代码",
    minWidth: 100,
  },
  {
    prop: "receiptType",
    label: "发票类型",
    minWidth: 100,
    formatter: (val) => {
      return { 1: "普通", 2: "专用" }[val]
    },
  },
  {
    prop: "buyerName",
    label: "购方名称",
    minWidth: 100,
  },
  {
    prop: "buyerIdNumber",
    label: "购方识别号",
    minWidth: 100,
  },
  {
    prop: "sellerName",
    label: "销方名称",
    minWidth: 100,
  },
  {
    prop: "sellerIdNumber",
    label: "销方识别号",
    minWidth: 100,
  },
  {
    prop: "receiptAmount",
    label: "合计金额",
    minWidth: 100,
  },
  {
    prop: "receiptTaxAmount",
    label: "合计税额",
    minWidth: 100,
  },
  {
    prop: "receiptTotalAmount",
    label: "价税合计",
    minWidth: 100,
  },
  {
    prop: "internalRemark",
    label: "内部备注",
    minWidth: 100,
  },
  {
    prop: "receiptRemark",
    label: "发票备注",
    minWidth: 100,
  },
  {
    prop: "createTime",
    label: "申请时间",
    minWidth: 100,
  },
  {
    prop: "createUserName",
    label: "申请人",
    minWidth: 100,
  },
  {
    prop: "receiptDate",
    label: "开票日期",
    minWidth: 100,
  },
  {
    prop: "approvalStatus",
    label: "审批状态",
    minWidth: 100,
    formatter: (val) => {
      return { 1: "待审核", 2: "通过", 3: "驳回" }[val]
    },
  },
  {
    prop: "pushStatus",
    label: "推送状态",
    minWidth: 100,
    formatter: (val) => {
      return { 0: "待推送", 1: "已推送", "-1": "失败" }[val]
    },
  },
  {
    prop: "billingStatus",
    label: "开票状态",
    minWidth: 100,
    formatter: (val) => {
      return { 0: "待开票", 1: "已开票", "-1": "已作废", "-2": "已红冲","2":"已红冲","3":"已作废" }[val]
    },
  },
  {
    prop: "operate",
    label: "操作",
    width: 200,
    slot: true,
    slotName: "operate",
    fixed: "right",
    overHidden: false
  },
]);
let tableData = ref([]);

let pageParam = reactive({
  total: 0,
  current: 1,
  size: 20
});
let onPageChange = (e) => {
  pageParam.current = e.page;
  pageParam.size = e.limit;
  getList();
};

let searchParam = reactive({
  applyTime: "",
  approvalStatus: "",
  pushStatus: "",
  billingStatus: "",
  receiptNumber: "",
});

// 1-待审核 2-通过 3-驳回
let stateOptions = ref([
  {
    label: "待审核",
    value: 1,
  },
  {
    label: "通过",
    value: 2,
  },
  {
    label: "驳回",
    value: 3,
  },
]);

// 0-待推送 1-已推送 -1-失败
let pushOptions = ref([
  {
    label: "待推送",
    value: 0,
  },
  {
    label: "已推送",
    value: 1,
  },
  {
    label: "失败",
    value: -1,
  }
])

// 0-待开票 1-已开票 -1-已作废 -2-已红冲
let invoiceStateOptions = ref([
  {
    label: "待开票",
    value: 0,
  },
  {
    label: "已开票",
    value: 1,
  },
  {
    label: "已作废",
    value: -1,
  },
  {
    label: "已红冲",
    value: -2,
  },
]);

let imgDialogRef = ref(null);
let imgDialogRef2 = ref(null);
let infoDialogRef = ref(null);

// 搜索
let searchHandler = () => {
  getList();
};
// 重置
let resetHandler = () => {
  for (let key in searchParam) {
    searchParam[key] = "";
  }
  getList();
};

// 列表导出
let exportHandler = async () => {
  let time = searchParam.applyTime;
  let res = await invoiceListApi.exportFIle({
    startCreateTime: time ? time[0] : "",
    endCreateTime: time ? time[1] : "",
    approvalStatus: searchParam.approvalStatus,
    pushStatus: searchParam.pushStatus,
    billingStatus: searchParam.billingStatus,
    receiptNumber: searchParam.receiptNumber,
  });
  if (res) {
    exportFile(res, "开票列表");
  }
};

// 查看
let viewHandler = (row) => {
    let fileUrl =  row.fileAddress;
    let type = fileUrl.substring(fileUrl.lastIndexOf('.')).toLowerCase();
    if(type ==='.pdf'){
        imgDialogRef2.value.openHandler("查看发票", row);
    }
    if(type==='.ofd'){
        imgDialogRef.value.openHandler("查看发票", row);
    }
};

// 详情
let detailHandler = (row) => {
  infoDialogRef.value.openHandler("详情", row);
};

// 数据选择
let selectItem = ref([]);
let onSelectChange = (arr) => {
  selectItem.value = arr;
};

let optionHandler = (type) => {
  // 等OA接口
  if (!selectItem.value.length) {
    ElNotification.warning("请选择需要操作的数据");
    return
  }
  if (type === "invalid") { // 作废
  } else if (type === "replace") { // 红冲
    form.status = '';
    dialogVisible.value = true;
  } else if (type === "push") { // 推送
      ElMessageBox.confirm(`确认推送该发票吗？`, "提示", {
          confirmButtonText: "确认",
          confirmButtonClass: "button_view",
          cancelButtonText: "取消",
          cancelButtonClass: "button_cancel2"
      }).then((value) => {
          if(value==='confirm'){
              const loading = ElLoading.service({
                  lock: true,
                  text: 'Loading...',
                  background: 'rgba(0, 0, 0, 0.7)',
              })
              invoiceListApi.push({id:selectItem.value[0].receiptId}).then(res=>{
                  loading.close();
                  if(res.code==='200'){
                      ElMessage.success('推送成功!');
                      getList();
                  }
              });
          }
      });
  }
};

/**
 * 红冲确认
 */
const confirm = () => {
  if(form.status===''){
      return ElMessage.warning('请选择红冲原因!');
  }
  let params = {
      id:selectItem.value[0].receiptId,
      hcyy:form.status
  }
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
  invoiceListApi.red(params)
      .then(res=>{
        loading.close();
        if(res.code==='200'){
            ElMessage.success('红冲成功!');
            getList();
            dialogVisible.value = false;
        }
  });
}

// 获取开票列表
let getList = async () => {
  let time = searchParam.applyTime;
  let res = await invoiceListApi.getPageList({
    pageNum: pageParam.current,
    pageSize: pageParam.size,
    param: {
      startCreateTime: time ? time[0] : "",
      endCreateTime: time ? time[1] : "",
      approvalStatus: searchParam.approvalStatus,
      pushStatus: searchParam.pushStatus,
      billingStatus: searchParam.billingStatus,
      receiptNumber: searchParam.receiptNumber,
    }
  });
  if (res.data) {
    tableData.value = res.data.content;
    pageParam.total = res.data.totalSize;
  }
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
:deep(.el-date-editor) {
  height: 100%;
}

.p-r10 {
  padding-right: 10px;
}
</style>
